<?php
require_once 'Examenes/Examen.class.php';
require_once 'Examenes/RuleProvider.class.php';
class ExamenProvider {

	public static function saveExamen(Examen $examen) {

		$registry = Zend_Registry :: getInstance();
		$config = $registry->config;

		$db = Zend_Db :: factory('Mysqli', array (
			'host' => $config->database->host,
			'username' => $config->database->username,
			'password' => $config->database->password,
			'dbname' => $config->database->name
		));

		$db->insert('EXAMEN', $examen->toDbArray());
		$id = $db->lastInsertId();
		foreach ($examen->getRules() as $rule) {
			$arrayInsert = array (
				'EXAMEN_ID' => $id,
			'REGLAS_HABILIDAD' => $rule->getHabilidad(),
			'REGLAS_NIVEL' => $rule->getNivel(),
			'REGLAS_TIPO_REACTIVO' => $rule->getTipoReactivo(),
			'REGLAS_NUMERO_PREGUNTAS' => $rule->getNumeroPreguntas(),
			'REGLAS_PESO' => $rule->getPuntaje()
			);
			$db->insert('REGLAS', $arrayInsert);
		}

	}

	public static function getExamenes() {
		$registry = Zend_Registry :: getInstance();
		$config = $registry->config;

		$db = Zend_Db :: factory('Mysqli', array (
			'host' => $config->database->host,
			'username' => $config->database->username,
			'password' => $config->database->password,
			'dbname' => $config->database->name
		));

		$rs = $db->fetchAssoc('SELECT ' .
		'EXAMEN_ID AS ID, ' .
		'EXAMEN_NOMBRE AS NOMBRE, ' .
		'EXAMEN_DESCRIPCION AS DESCRIPCION ' .
		'FROM ' .
		'EXAMEN ');

		$arrayExamenes = array ();

		foreach ($rs as $row) {
			$examen = new Examen();
			$examen->setId($row['ID']);
			$examen->setDescripcion($row['DESCRIPCION']);
			$examen->setNombre($row['NOMBRE']);
			$arrayRules = RuleProvider :: getRules($row['ID']);
			foreach ($arrayRules as $rule) {
				$examen->addRule($rule);
			}
			$arrayExamenes[] = $examen;
		}
		return $arrayExamenes;
	}

	public static function getExamen($examenId) {
		$registry = Zend_Registry :: getInstance();
		$config = $registry->config;

		$db = Zend_Db :: factory('Mysqli', array (
			'host' => $config->database->host,
			'username' => $config->database->username,
			'password' => $config->database->password,
			'dbname' => $config->database->name
		));
		$db->setFetchMode(Zend_Db :: FETCH_ASSOC);
		$row = $db->fetchRow('SELECT ' .
		'EXAMEN_ID AS ID, ' .
		'EXAMEN_NOMBRE AS NOMBRE, ' .
		'EXAMEN_DESCRIPCION AS DESCRIPCION ' .
		'FROM ' .
		'EXAMEN WHERE EXAMEN_ID =' . $examenId);

		$examen = new Examen();
		$examen->setId($row['ID']);
		$examen->setDescripcion($row['DESCRIPCION']);
		$examen->setNombre($row['NOMBRE']);
		$arrayRules = RuleProvider :: getRules($row['ID']);
		foreach ($arrayRules as $rule) {
			$examen->addRule($rule);
		}
		return $examen;
	}
}
?>